# -*- coding: utf-8 -*-
"""
@Time : 2023/7/28 16:50
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : update_borrower_valid.py
"""

import sys
from flask_restful import Resource, reqparse

from service.mysql_connect import MySQLConnected
from service.config_import import load_yaml

sys.path.append('..')

parser = reqparse.RequestParser()
parser.add_argument('person_id', type=int, help="参数person_id不能为空", required=True)


class UpdateBorrowerValid(Resource):
    def post(self):
        args = parser.parse_args()
        update_person_id = args.get('person_id')
        yaml_config_path = "config_info.yaml"
        params = load_yaml(yaml_config_path)
        dbinfo = params['databases']['library_db_info']
        # print(dbinfo)
        db = params['databases']['library_db_name']
        connected = MySQLConnected(dbinfo)

        sql_check_exist = "select * from " + db + ".borrowers where id = %s"
        connected.cur.execute(sql_check_exist, str(update_person_id))
        exists = connected.cur.fetchall()
        if not exists:
            return {'content': '不存在对应人员，请确认', 'result': 'failure'}

        sql_for_check_no_return = "select * from " + db + ".books_borrowers_relation " + \
                                  "where borrower_id = %s and return_time is null"
        connected.cur.execute(sql_for_check_no_return, str(update_person_id))
        res = connected.cur.fetchall()
        print(res)
        if res:
            return {'content': '该人名下存在未归还书籍，不可更新状态', 'result': 'failure'}
        sql = "update " + db + ".borrowers set valid = not valid where id = %s"
        connected.cur.execute(sql, str(update_person_id))

        connected.con.commit()
        connected.cur.close()
        connected.con.close()

        return {'content': "人员在/离职状态更新成功", 'result': 'success'}
